using Masuit.Tools;
using Simple.Contracts.Contracts;
using Simple.Contracts.Models;
using Simple.Contracts.Models.Common;
using Simple.Repository;
using Simple.Repository.SimpleEntitys;
using Simple.Services;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Simple.Services.Services
{
    /// <summary>
    /// 照护任务分类服务实现
    /// </summary>
    public class CareMissionCategorizeService : BaseService, ICareMissionCategorizeService
    {
        public CareMissionCategorizeService(FreeSqlCloud freeSqlCloud, CurrentAccount currentAccount) : base(freeSqlCloud, currentAccount) { }

        /// <summary>
        /// 获取照护任务分类列表
        /// </summary>
        /// <param name="input">照护任务分类列表输入参数</param>
        /// <returns>照护任务分类列表</returns>
        public async Task<Result<List<CareMissionCategorizeDto>>> List(CareMissionCategorizeListInput input)
        {
            var query = _simpleFreeSql.Select<CareMissionCategorize>()
                    .Where(x => x.IsDelete == 0)
                    .WhereIf(!input.SelectPlatform.HasValue, x => (x.CompanyId == 1 || x.CompanyId == _currentAccount.CompanyId))
                    .WhereIf(input.SelectPlatform.HasValue && input.SelectPlatform.Value == true, x => x.CompanyId == 1)
                    .WhereIf(input.SelectPlatform.HasValue && input.SelectPlatform.Value == false, x => x.CompanyId == _currentAccount.CompanyId);

            var categories = new List<CareMissionCategorize>();
            if (!input.SelectPlatform.HasValue)
            {
                // 查看平台&公司内的分类和照护任务，先看公司自己维护的，再看平台维护的
                categories = await query.OrderByDescending(x => x.CompanyId).OrderBy(x => x.Sort).OrderByDescending(x => x.UpdateTime).ToListAsync();
            }
            else
            {
                categories = await query.OrderBy(x => x.Sort).OrderByDescending(x => x.UpdateTime).ToListAsync();
            }

            var resultList = new List<CareMissionCategorizeDto>();
            bool isSearchDailyMission = input.Time == "每日不限制时间段" && input.Name.IsNullOrEmpty();
            bool isNotDailyMission = input.Time == "根据需求及老人情况" && input.Name.IsNullOrEmpty();
            // 搜索特殊时间段
            int? searchStartTime = null;
            int? searchEndTime = null;
            if (!input.Time.IsNullOrEmpty() && input.Name.IsNullOrEmpty() && input.Time!.Contains("-"))
            {
                var searchTimes = input.Time.Replace(":", "").Split('-');
                searchStartTime = int.Parse(searchTimes[0]);
                searchEndTime = int.Parse(searchTimes[1]);
            }
            foreach (var category in categories)
            {

                var dto = new CareMissionCategorizeDto
                {
                    Id = category.Id,
                    CompanyId = category.CompanyId,
                    Name = category.Name,
                    Sort = category.Sort,
                    CreateTime = category.CreateTime,
                    CreateBy = category.CreateBy,
                    UpdateTime = category.UpdateTime,
                    UpdateBy = category.UpdateBy
                };

                // 根据参数决定是否返回分类下的照护任务列表
                if (input?.IncludeMissions ?? false)
                {
                    var missions = await _simpleFreeSql.Select<CareMission>()
                        .Where(x => x.IsDelete == 0 && x.CategorizeId == category.Id)
                        .WhereIf(!input.Name.IsNullOrEmpty(), x => x.Name.Contains(input.Name!))
                        .WhereIf(isSearchDailyMission, x => x.IsDailyMission == 1 && (x.DailyMissionStartTimeValue == null || x.DailyMissionEndTimeValue == null)) //搜索：每日不限实时时段任务
                        .WhereIf(isNotDailyMission, x => x.IsDailyMission == 0)                                                                                    //搜索：根据需求及老人情况
                        .WhereIf(searchStartTime.HasValue && searchEndTime.HasValue, x => searchEndTime!.Value>= x.DailyMissionEndTimeValue && x.DailyMissionStartTimeValue>= searchStartTime!.Value) //搜索：根据特殊时间段
                        .OrderByDescending(x => x.IsDailyMission)
                        .OrderBy(x => x.DailyMissionStartTime)
                        .ToListAsync(x => new CareMissionDto
                        {
                            Id = x.Id,
                            CompanyId = x.CompanyId,
                            CategorizeId = x.CategorizeId,
                            Name = x.Name,
                            Description = x.Description,
                            DailyMissionEndTime = x.DailyMissionEndTime,
                            DailyMissionStartTimeValue = x.DailyMissionStartTimeValue,
                            DailyMissionEndTimeValue = x.DailyMissionEndTimeValue,
                            DailyMissionStartTime = x.DailyMissionStartTime,
                            DailyMissionExecutionCount = x.DailyMissionExecutionCount,
                            IsDailyMission = x.IsDailyMission,
                            CreateTime = x.CreateTime,
                            CreateBy = x.CreateBy,
                            UpdateTime = x.UpdateTime,
                            UpdateBy = x.UpdateBy,
                            Sort = x.Sort
                        });
                    dto.CareMissions = missions;
                }

                // 查看平台内的分类和照护任务，分类下没有照护任务不用返回
                if (input!.SelectPlatform.HasValue && input.SelectPlatform.Value == true)
                {
                    if (!dto.CareMissions.Any())
                    {
                        continue;
                    }
                }

                // 查看平台&公司内的分类和照护任务，分类下没有照护任务不用返回
                if (!input.SelectPlatform.HasValue)
                {
                    if (!dto.CareMissions.Any())
                    {
                        continue;
                    }
                }

                resultList.Add(dto);
            }
            return Result<List<CareMissionCategorizeDto>>.Success(resultList);
        }

        /// <summary>
        /// 保存照护任务分类信息
        /// </summary>
        /// <param name="input">照护任务分类保存输入参数</param>
        /// <returns>保存结果</returns>
        public async Task<Result<long>> Save(CareMissionCategorizeSaveInput input)
        {
            if (string.IsNullOrEmpty(input.Name))
            {
                return Result<long>.FriendlyReminder("分类名称不能为空");
            }

            long categorizeId = 0;
            if (input.Id.HasValue && input.Id != 0)
            {
                // 更新分类
                var categorize = await _simpleFreeSql.Select<CareMissionCategorize>()
                    .Where(x => x.Id == input.Id.Value && x.CompanyId == _currentAccount.CompanyId && x.IsDelete == 0)
                    .FirstAsync();

                if (categorize == null)
                {
                    return Result<long>.FriendlyReminder("该分类不存在或已被删除");
                }

                // 检查名称是否重复
                var exists = await _simpleFreeSql.Select<CareMissionCategorize>()
                    .Where(x => x.Name == input.Name && x.Id != input.Id.Value && x.CompanyId == _currentAccount.CompanyId && x.IsDelete == 0)
                    .AnyAsync();

                if (exists)
                {
                    return Result<long>.FriendlyReminder("该分类名称已存在");
                }

                // 更新数据
                categorize.Name = input.Name;
                categorize.Sort = input.Sort;
                categorize.UpdateBy = _currentAccount.EmployeeId;
                categorize.UpdateTime = DateTime.Now;

                await _simpleFreeSql.Update<CareMissionCategorize>().SetSource(categorize).ExecuteAffrowsAsync();
                categorizeId = categorize.Id;
            }
            else
            {
                // 新增分类
                // 检查名称是否重复
                var exists = await _simpleFreeSql.Select<CareMissionCategorize>()
                    .Where(x => x.Name == input.Name && x.CompanyId == _currentAccount.CompanyId && x.IsDelete == 0)
                    .AnyAsync();

                if (exists)
                {
                    return Result<long>.FriendlyReminder("该分类名称已存在");
                }

                var categorize = new CareMissionCategorize()
                {
                    CompanyId = _currentAccount.CompanyId,
                    Name = input.Name,
                    Sort = input.Sort,
                    CreateBy = _currentAccount.EmployeeId,
                    CreateTime = DateTime.Now,
                    UpdateBy = _currentAccount.EmployeeId,
                    UpdateTime = DateTime.Now,
                    IsDelete = 0
                };

                categorizeId = await _simpleFreeSql.Insert<CareMissionCategorize>(categorize).ExecuteIdentityAsync();
            }

            return Result<long>.Success(categorizeId);
        }

        /// <summary>
        /// 更新照护任务分类排序值
        /// </summary>
        /// <param name="input">排序更新输入</param>
        /// <returns>更新结果</returns>
        public async Task<Result<bool>> UpdateSort(CareMissionCategorizeSortInput input)
        {
            await _simpleFreeSql.Update<CareMissionCategorize>()
                .Set(x => x.Sort, input.Sort)
                .Set(x => x.UpdateTime, DateTime.Now)
                .Set(x => x.UpdateBy, _currentAccount.EmployeeId)
                .Where(x => x.Id == input.Id && x.CompanyId == _currentAccount.CompanyId && x.IsDelete == 0)
                .ExecuteAffrowsAsync();
            return Result<bool>.Success(true);
        }

        /// <summary>
        /// 删除照护任务分类
        /// </summary>
        /// <param name="careMissionCategorizeId"></param>
        /// <returns></returns>
        public async Task<Result<bool>> Delete(long careMissionCategorizeId)
        {
            // 检查分类下是否有照护任务
            var hasMissions = await _simpleFreeSql.Select<CareMission>()
                .Where(x => x.CompanyId == _currentAccount.CompanyId && x.CategorizeId == careMissionCategorizeId && x.IsDelete == 0)
                .AnyAsync();

            if (hasMissions)
            {
                return Result<bool>.FriendlyReminder("分类下有照护任务，无法删除");
            }

            // 软删除分类
            await _simpleFreeSql.Update<CareMissionCategorize>()
                .Set(x => x.IsDelete, 1)
                .Set(x => x.UpdateBy, _currentAccount.EmployeeId)
                .Set(x => x.UpdateTime, DateTime.Now)
                .Where(x => x.CompanyId == _currentAccount.CompanyId && x.Id == careMissionCategorizeId)
                .ExecuteAffrowsAsync();

            return Result<bool>.Success(true);
        }
    }
}